package com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.chargePayment.entity.SmsWnsChargePaymentRecord;
import com.xyht.sca_s.student_manage_system.modules.chargePayment.mapper.SmsWnsChargePaymentRecordMapper;
import com.xyht.sca_s.student_manage_system.modules.common.constant.TaskNameExample;
import com.xyht.sca_s.student_manage_system.modules.common.constant.TaskTypeConstant;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTask;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTaskDetail;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgUserRelation;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgUserRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsUserStudentRelation;
import com.xyht.sca_s.student_manage_system.modules.student.entity.resp.SmsStudentInfoResp;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsStudentInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsUserStudentRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.constant.ChargePlanConstant;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.SmsWnsChargeCategoryDetail;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.SmsWnsChargeOrgItem;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.SmsWnsChargePlan;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.SmsWnsChargePlanStudentStatus;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.req.ChargeItemBatchAddReq;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.req.ChargeItemBatchExportReq;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.req.OrgOrStuInfoReq;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.req.SmsWnsChargeOrgItemReq;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.resp.CategoryItemResp;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.resp.SmsWnsChargeOrgItemResp;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.resp.SmsWnsStudentPaymentRecordResp;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.mapper.SmsWnsChargeCategoryDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.mapper.SmsWnsChargeOrgItemMapper;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.mapper.SmsWnsChargePlanMapper;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.mapper.SmsWnsChargePlanStudentStatusMapper;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.service.SmsWnsChargeOrgItemService;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.service.SmsWnsChargePlanService;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.util.CategoryItemUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskDetailReason.*;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.*;
import static com.xyht.sca_s.student_manage_system.modules.signUp.constant.SmsSignUpCommonConstant.PER_SHEET_NUM;
import static com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.constant.ChargePlanConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.constant.IsPaymentTypeConstant.PAYMENT_TYPE_IS;
import static com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.constant.IsPaymentTypeConstant.PAYMENT_TYPE_IS_NOT;

/**
 * <p>
 * 各专业收费项表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2024-01-15
 */
@Service
public class SmsWnsChargeOrgItemServiceImpl extends ServiceImpl<SmsWnsChargeOrgItemMapper, SmsWnsChargeOrgItem> implements SmsWnsChargeOrgItemService {
    @Resource
    private SmsWnsChargePlanService smsWnsChargePlanService;
    @Resource
    private SmsOrgStructureMapper smsOrgStructureMapper;
    @Resource
    private SmsUserMapper smsUserMapper;
    @Resource
    private SmsWnsChargePlanMapper smsWnsChargePlanMapper;
    @Resource
    private SmsWnsChargeCategoryDetailMapper smsWnsChargeCategoryDetailMapper;
    @Resource
    private CategoryItemUtil categoryItemUtil;
    @Resource
    private SmsStudentInfoMapper smsStudentInfoMapper;
    @Resource
    private SmsImportTaskMapper smsImportTaskMapper;
    @Resource
    private PlatformTransactionManager transactionManager;
    @Resource
    private SmsImportTaskDetailMapper smsImportTaskDetailMapper;
    @Resource
    private SmsOrgUserRelationMapper smsOrgUserRelationMapper;
    @Resource
    private SmsUserStudentRelationMapper smsUserStudentRelationMapper;
    @Resource
    private SmsWnsChargePaymentRecordMapper smsWnsChargePaymentRecordMapper;
    @Resource
    private SmsWnsChargePlanStudentStatusMapper smsWnsChargePlanStudentStatusMapper;

    @Override
    @Transactional
    public ResponseResult addCategoryItem(SmsWnsChargeOrgItemReq categoryItemReq) {
        if (isNullOrEmpty(categoryItemReq.getPlanId(), categoryItemReq.getCategoryDetailId(), categoryItemReq.getOrgId(),
                categoryItemReq.getAmount())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        // 收费金额不可小于0
        if (categoryItemReq.getAmount().compareTo(new BigDecimal(0)) < 0) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        // 查询收费计划是否存在
        SmsWnsChargePlan plan = smsWnsChargePlanService.getById(categoryItemReq.getPlanId());
        if (plan == null) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_PLAN_NOT_EXIST);
        }

        // 校验传入元素是否在范围内
        List<String> idList = JSON.parseArray(plan.getIdList(), String.class);
        if (!idList.contains(categoryItemReq.getOrgId())) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_PLAN_RANGE_OUT_OF_TYPE);
        }

        // 查询详细分类是否存在
        SmsWnsChargeCategoryDetail chargeCategoryDetail = smsWnsChargeCategoryDetailMapper.selectById(categoryItemReq.getCategoryDetailId());
        if (chargeCategoryDetail == null) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_DETAIL_NOT_EXIST);
        }

        // 保存收费项信息
        SmsWnsChargeOrgItem chargeItem = new SmsWnsChargeOrgItem();
        BeanUtils.copyProperties(categoryItemReq, chargeItem);
        chargeItem.setCategoryId(chargeCategoryDetail.getCategoryId());
        this.save(chargeItem);

        return CommonResult.success(chargeItem.getId());
    }

    @Override
    @Transactional
    public ResponseResult updateCategoryItem(SmsWnsChargeOrgItemReq categoryItemReq) {
        if (isNullOrEmpty(categoryItemReq.getId(), categoryItemReq.getAmount())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        // 校验收费项是否存在
        SmsWnsChargeOrgItem chargeItem = this.getById(categoryItemReq.getId());
        if (chargeItem == null) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_ORG_ITEM_NOT_EXIST);
        }

        // 收费金额不可小于0
        if (categoryItemReq.getAmount().compareTo(new BigDecimal(0)) < 0) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        chargeItem.setAmount(categoryItemReq.getAmount());

        if (!isNullOrEmpty(categoryItemReq.getDescription())) {
            chargeItem.setDescription(categoryItemReq.getDescription());
        }

        // 保存收费项信息
        this.updateById(chargeItem);

        return CommonResult.success();
    }

    @Override
    public ResponseResult listCategoryItem(Integer pageNum, Integer pageSize, String planId, String searchStr) {
        SmsWnsChargePlan plan = smsWnsChargePlanMapper.selectById(planId);
        if (plan == null) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_PLAN_NOT_EXIST);
        }

        if (isNullOrEmpty(plan.getDetailIdList())) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_PLAN_DETAIL_LIST_NOT_EXIST);
        }

        // 未初始化先进行初始化
        if (!plan.getIsInitialized()) {
            boolean initSuccess = categoryItemUtil.initializeCategoryItemByPlanId(planId);
            if (!initSuccess) {
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
        }

        List<SmsWnsChargeCategoryDetail> detailList = smsWnsChargeCategoryDetailMapper.selectBatchIds(JSON.parseArray(plan.getDetailIdList(), String.class));

        // 获取收费粒度
        Integer rangeType = plan.getRangeType();
        List<String> idList = JSON.parseArray(plan.getIdList(), String.class);
        if (rangeType != CHARGE_PLAN_RANGE_TYPE_USER) { // 粒度不等于学生
            LambdaQueryWrapper<SmsOrgStructure> queryWrapper = new LambdaQueryWrapper<SmsOrgStructure>()
                    .in(SmsOrgStructure::getId, idList)
                    .orderByDesc(SmsOrgStructure::getCreateTime);

            if (!isNullOrEmpty(searchStr)) {
                StringUtils.deleteWhitespace(searchStr);
                queryWrapper.and(i -> i.like(SmsOrgStructure::getOrgName, searchStr));
            }

            Page<SmsOrgStructure> page = new Page<>(pageNum, pageSize);
            smsOrgStructureMapper.selectPage(page, queryWrapper);
            List<CategoryItemResp> collect = page.getRecords().stream().map(org -> {
                CategoryItemResp categoryItemResp = new CategoryItemResp();
                categoryItemResp.setOrgId(org.getId());

                switch (rangeType) {
                    case CHARGE_PLAN_RANGE_TYPE_MAJOR:
                        categoryItemResp.setGradeName(plan.getGrade());
                        categoryItemResp.setMajorName(org.getOrgName());
                        break;
                    case CHARGE_PLAN_RANGE_TYPE_CLASS:
                        categoryItemResp.setClassName(org.getOrgName());
                        break;
                }

                List<SmsWnsChargeOrgItemResp> chargeItemRespList = new ArrayList<>();
                for (SmsWnsChargeCategoryDetail categoryDetail : detailList) {
                    SmsWnsChargeOrgItem chargeItem = this.getOne(new LambdaQueryWrapper<SmsWnsChargeOrgItem>()
                            .eq(SmsWnsChargeOrgItem::getPlanId, planId)
                            .eq(SmsWnsChargeOrgItem::getOrgId, org.getId())
                            .eq(SmsWnsChargeOrgItem::getCategoryDetailId, categoryDetail.getId()));
                    SmsWnsChargeOrgItemResp chargeItemResp = new SmsWnsChargeOrgItemResp();
                    BeanUtils.copyProperties(chargeItem, chargeItemResp);
                    chargeItemResp.setCategoryDetailName(categoryDetail.getName());
                    chargeItemRespList.add(chargeItemResp);
                }

                categoryItemResp.setChargeItemList(chargeItemRespList);
                return categoryItemResp;
            }).collect(Collectors.toList());

            return CommonResult.success(collect, (int) page.getTotal());
        } else { // 粒度为学生
            LambdaQueryWrapper<SmsStudentInfo> queryWrapper = new LambdaQueryWrapper<SmsStudentInfo>()
                    .in(SmsStudentInfo::getId, idList)
                    .orderByDesc(SmsStudentInfo::getStuClass);

            if (!isNullOrEmpty(searchStr)) {
                StringUtils.deleteWhitespace(searchStr);
                queryWrapper.and(i -> i.like(SmsStudentInfo::getStuName, searchStr).or()
                        .like(SmsStudentInfo::getStuGrade, searchStr).or()
                        .like(SmsStudentInfo::getStuMajor, searchStr).or()
                        .like(SmsStudentInfo::getStuClass, searchStr));
            }

            Page<SmsStudentInfo> page = new Page<>(pageNum, pageSize);
            smsStudentInfoMapper.selectPage(page, queryWrapper);
            List<CategoryItemResp> collect = page.getRecords().stream().map(stuInfo -> {
                CategoryItemResp categoryItemResp = new CategoryItemResp();
                categoryItemResp.setGradeName(stuInfo.getStuGrade());
                categoryItemResp.setMajorName(stuInfo.getStuMajor());
                categoryItemResp.setClassName(stuInfo.getStuClass());
                categoryItemResp.setStuName(stuInfo.getStuName());
                categoryItemResp.setStuNo(stuInfo.getStuNo());

                List<SmsWnsChargeOrgItemResp> chargeItemRespList = new ArrayList<>();
                for (SmsWnsChargeCategoryDetail categoryDetail : detailList) {
                    SmsWnsChargeOrgItem chargeItem = this.getOne(new LambdaQueryWrapper<SmsWnsChargeOrgItem>()
                            .eq(SmsWnsChargeOrgItem::getPlanId, planId)
                            .eq(SmsWnsChargeOrgItem::getOrgId, stuInfo.getId())
                            .eq(SmsWnsChargeOrgItem::getCategoryDetailId, categoryDetail.getId()));
                    SmsWnsChargeOrgItemResp chargeItemResp = new SmsWnsChargeOrgItemResp();
                    BeanUtils.copyProperties(chargeItem, chargeItemResp);
                    chargeItemResp.setCategoryDetailName(categoryDetail.getName());
                    chargeItemRespList.add(chargeItemResp);
                }

                categoryItemResp.setChargeItemList(chargeItemRespList);
                return categoryItemResp;
            }).collect(Collectors.toList());

            return CommonResult.success(collect, (int) page.getTotal());
        }
    }

    @Override
    public ResponseResult categoryItemDetail(String id) {
        SmsWnsChargeOrgItem category = this.getById(id);
        if (category == null) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_NOT_EXIST);
        }

        SmsWnsChargeOrgItemResp categoryResp = new SmsWnsChargeOrgItemResp();
        BeanUtils.copyProperties(category, categoryResp);

        return CommonResult.success(categoryResp);
    }

    @Override
    @Async
    public Future<ResponseResult> batchExportChargeItem(ChargeItemBatchExportReq chargeItemBatchExportReq, HttpServletResponse response) {
        // 校验参数
        if (isNullOrEmpty(chargeItemBatchExportReq.getPlanId())) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }

        // 校验收费计划是否存在
        SmsWnsChargePlan plan = smsWnsChargePlanService.getById(chargeItemBatchExportReq.getPlanId());
        if (plan == null) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WNS_CHARGE_PLAN_NOT_EXIST));
        }

        // 校验计划是否初始化(指定收费项)
        if (!plan.getIsInitialized()) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WNS_CHARGE_PLAN_DETAIL_LIST_NOT_EXIST));
        }

        // 校验收费类别详情是否存在
        List<SmsWnsChargeCategoryDetail> detailList = smsWnsChargeCategoryDetailMapper.selectList(new LambdaQueryWrapper<SmsWnsChargeCategoryDetail>()
                .in(SmsWnsChargeCategoryDetail::getId, JSON.parseArray(plan.getDetailIdList(), String.class))
                .orderByAsc(SmsWnsChargeCategoryDetail::getCategorySort)
                .orderByAsc(SmsWnsChargeCategoryDetail::getSort));
        if (detailList.isEmpty()) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_DETAIL_NOT_EXIST));
        }

        // 获取收费粒度
        Integer rangeType = plan.getRangeType();
        List<String> idList = JSON.parseArray(plan.getIdList(), String.class);

        // 收集导出数据
        List<CategoryItemResp> categoryItemRespList = new ArrayList<>();
        if (rangeType != CHARGE_PLAN_RANGE_TYPE_USER) { // 粒度不等于学生
            List<SmsOrgStructure> orgStructureList = smsOrgStructureMapper.selectBatchIds(idList);
            if (rangeType == CHARGE_PLAN_RANGE_TYPE_MAJOR) {
                categoryItemRespList = orgStructureList.stream().map(org -> {
                    CategoryItemResp categoryItemResp = new CategoryItemResp();
                    categoryItemResp.setGradeName(plan.getGrade());
                    categoryItemResp.setMajorName(org.getOrgName());

                    List<SmsWnsChargeOrgItemResp> chargeItemList = categoryItemUtil.getCategoryItemRespList(plan.getId(), String.valueOf(org.getId()));
                    List<SmsWnsChargeOrgItemResp> chargeItemOrderBySortList = new ArrayList<>();
                    for (SmsWnsChargeCategoryDetail chargeCategoryDetail : detailList) {
                        List<SmsWnsChargeOrgItemResp> filterChargeItemList = chargeItemList.stream().filter(chargeItem -> chargeItem.getCategoryDetailId().equals(chargeCategoryDetail.getId())).collect(Collectors.toList());
                        chargeItemOrderBySortList.add(filterChargeItemList.get(0));
                    }

                    categoryItemResp.setChargeItemList(chargeItemOrderBySortList);

                    return categoryItemResp;
                }).collect(Collectors.toList());
            } else if (rangeType == CHARGE_PLAN_RANGE_TYPE_CLASS) {
                categoryItemRespList = orgStructureList.stream().map(org -> {
                    CategoryItemResp categoryItemResp = new CategoryItemResp();
                    categoryItemResp.setClassName(org.getOrgName());

                    List<SmsWnsChargeOrgItemResp> chargeItemList = categoryItemUtil.getCategoryItemRespList(plan.getId(), String.valueOf(org.getId()));
                    List<SmsWnsChargeOrgItemResp> chargeItemOrderBySortList = new ArrayList<>();
                    for (SmsWnsChargeCategoryDetail chargeCategoryDetail : detailList) {
                        List<SmsWnsChargeOrgItemResp> filterChargeItemList = chargeItemList.stream().filter(chargeItem -> chargeItem.getCategoryDetailId().equals(chargeCategoryDetail.getId())).collect(Collectors.toList());
                        chargeItemOrderBySortList.add(filterChargeItemList.get(0));
                    }

                    categoryItemResp.setChargeItemList(chargeItemOrderBySortList);

                    return categoryItemResp;
                }).collect(Collectors.toList());
            }
        } else {
            List<SmsStudentInfo> studentInfoList = smsStudentInfoMapper.selectBatchIds(idList);
            categoryItemRespList = studentInfoList.stream().map(stuInfo -> {
                CategoryItemResp categoryItemResp = new CategoryItemResp();
                categoryItemResp.setGradeName(stuInfo.getStuGrade());
                categoryItemResp.setMajorName(stuInfo.getStuMajor());
                categoryItemResp.setClassName(stuInfo.getStuClass());
                categoryItemResp.setStuName(stuInfo.getStuName());
                categoryItemResp.setStuNo(stuInfo.getStuNo());

                List<SmsWnsChargeOrgItemResp> chargeItemList = categoryItemUtil.getCategoryItemRespList(plan.getId(), stuInfo.getId());
                List<SmsWnsChargeOrgItemResp> chargeItemOrderBySortList = new ArrayList<>();
                for (SmsWnsChargeCategoryDetail chargeCategoryDetail : detailList) {
                    List<SmsWnsChargeOrgItemResp> filterChargeItemList = chargeItemList.stream().filter(chargeItem -> chargeItem.getCategoryDetailId().equals(chargeCategoryDetail.getId())).collect(Collectors.toList());
                    chargeItemOrderBySortList.add(filterChargeItemList.get(0));
                }

                categoryItemResp.setChargeItemList(chargeItemOrderBySortList);

                return categoryItemResp;
            }).collect(Collectors.toList());
        }

        // 导出
        try {
            //声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            //获取sheet页数
            double sheetNum = Math.ceil((double) categoryItemRespList.size() / PER_SHEET_NUM);
            for (int k = 0; k < sheetNum; k++) {
                //生成一个 sheet页,设置 sheet页 名称为 "缴费项导出表"
                HSSFSheet sheet = workbook.createSheet("缴费项导出表" + (k + 1));
                //设置表格列宽度为 12
                sheet.setDefaultColumnWidth(12);

                //设置单元格的显示样式
                HSSFCellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
                cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                //设置单元格字体
                HSSFFont font = workbook.createFont();
                font.setFontHeightInPoints((short) 10);//字号
                font.setBold(true);//加粗
                cellStyle.setFont(font);

                //创建第一行表头
                HSSFRow headRow = sheet.createRow(0);
                //设置第一行数据
                int fixColumnNum = 6; //固定列数
                int detailListSize = detailList.size();
                int columnNum = fixColumnNum + detailListSize * 2;//列数
                for (int i = 0; i < columnNum; i++) {
                    //创建一个单元格
                    HSSFCell cell = headRow.createCell(i);
                    cell.setCellStyle(cellStyle);

                    String columnName;
                    switch (i) {
                        case 0:
                            columnName = "序号";
                            break;
                        case 1:
                            columnName = "年级名";
                            break;
                        case 2:
                            columnName = "专业名";
                            break;
                        case 3:
                            columnName = "班级名";
                            break;
                        case 4:
                            columnName = "学生姓名";
                            break;
                        case 5:
                            columnName = "学号";
                            break;
                        default:
                            if (i < fixColumnNum + detailListSize) {
                                columnName = detailList.get(i - fixColumnNum).getName();
                            } else {
                                columnName = detailList.get(i - fixColumnNum - detailListSize).getName() + "优惠金额";
                            }
                    }

                    //创建一个内容对象
                    HSSFRichTextString text = new HSSFRichTextString(columnName);
                    //将内容对象的文字内容写入到单元格中
                    cell.setCellValue(text);
                }

                //设置内容
                int range = PER_SHEET_NUM;
                //如果是最后一个 sheet 页, 修改 range 值
                if (k + 1 == sheetNum) {
                    range = categoryItemRespList.size() - PER_SHEET_NUM * k;
                }
                //设置其他行数据
                for (int i = 0; i < range; i++) {
                    //设置数据
                    CategoryItemResp categoryItemResp = categoryItemRespList.get(PER_SHEET_NUM * k + i);
                    //创建一行
                    HSSFRow row = sheet.createRow(i + 1);
                    //序号
                    row.createCell(0).setCellValue(new HSSFRichTextString(String.valueOf(i + 1)));
                    //设置该行数据
                    for (int j = 1; j < columnNum; j++) {
                        String data;
                        switch (j) {
                            case 1://年级名
                                data = categoryItemResp.getGradeName();
                                break;
                            case 2://专业名
                                data = categoryItemResp.getMajorName();
                                break;
                            case 3://班级名
                                data = categoryItemResp.getClassName();
                                break;
                            case 4://学生姓名
                                data = categoryItemResp.getStuName();
                                break;
                            case 5://学号
                                data = categoryItemResp.getStuNo();
                                break;
                            default://其他
                                if (j < fixColumnNum + detailListSize) {
                                    data = categoryItemResp.getChargeItemList().get(j - fixColumnNum).getAmount().toString();
                                } else {
                                    data = "0";
                                }
                        }
                        row.createCell(j).setCellValue(new HSSFRichTextString(data == null ? "" : data));
                    }
                }
            }

            //设置 response
            //response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("缴费项导出表.xlsx", "utf-8"));
            response.setCharacterEncoding("utf-8");
            response.setHeader("file-type", "download");
            response.setHeader("file-name", URLEncoder.encode("缴费项导出表.xlsx", "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
            //刷新缓冲
            response.flushBuffer();
            //workbook将Excel写入到response的输出流中，供页面下载
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            workbook.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        return null;
    }

    @Override
    @Async
    public Future<ResponseResult> batchAddChargeItem(ChargeItemBatchAddReq chargeItemBatchAddReq, String userId) {
        List<OrgOrStuInfoReq> orgOrStuInfoReqList = chargeItemBatchAddReq.getOrgOrStuInfoReqList();
        if (orgOrStuInfoReqList == null || orgOrStuInfoReqList.isEmpty()) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }

        SmsWnsChargePlan plan = smsWnsChargePlanMapper.selectById(chargeItemBatchAddReq.getPlanId());
        if (plan == null) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WNS_CHARGE_PLAN_NOT_EXIST));
        }

        // 校验计划是否指定收费项
        if (!plan.getIsInitialized()) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WNS_CHARGE_PLAN_DETAIL_LIST_NOT_EXIST));
        }

        // 校验收费类别详情是否存在
        List<String> detailIdList = JSON.parseArray(plan.getDetailIdList(), String.class);
        List<SmsWnsChargeCategoryDetail> detailList = smsWnsChargeCategoryDetailMapper.selectList(new LambdaQueryWrapper<SmsWnsChargeCategoryDetail>()
                .in(SmsWnsChargeCategoryDetail::getId, detailIdList)
                .orderByAsc(SmsWnsChargeCategoryDetail::getCategorySort)
                .orderByAsc(SmsWnsChargeCategoryDetail::getSort));
        if (detailList.isEmpty()) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_DETAIL_NOT_EXIST));
        }

        // 创建导入任务
        SmsImportTask smsImportTask = new SmsImportTask();
        smsImportTask.setTaskName(TaskNameExample.TASK_NAME_CHARGE_ITEM_IMPORT);
        smsImportTask.setUserId(userId);
        smsImportTask.setStatus(TASK_STATUS_DOING); // 任务状态 0:进行中
        smsImportTask.setTaskType(TaskTypeConstant.TASK_TYPE_CHARGE_ITEM_IMPORT);
        smsImportTaskMapper.insert(smsImportTask);
        String taskId = smsImportTask.getId();
        if (isNullOrEmpty(taskId)) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }

        // 批量导入新生信息
        int OFFSET_ROW = 1; // 初始化行数
        int taskStatus = TASK_STATUS_DONE; // 任务状态: 完成

        // 范围粒度(1.专业 2.班级 3.人员)
        Integer rangeType = plan.getRangeType();
        List<String> idList = JSON.parseArray(plan.getIdList(), String.class);
        for (int i = 0; i < orgOrStuInfoReqList.size(); i++) {
            //开启事务
            DefaultTransactionDefinition dt = new DefaultTransactionDefinition();
            // 嵌套事务 PROPAGATION_REQUIRES_NEW 每次开启一个新的事务
            dt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 设置嵌套事务
            TransactionStatus status = transactionManager.getTransaction(dt);
            try {
                OrgOrStuInfoReq orgOrStuInfoReq = orgOrStuInfoReqList.get(i);

                // 必填字段验证
                List<String> filterIdList = new ArrayList<>();
                if (rangeType == CHARGE_PLAN_RANGE_TYPE_MAJOR) {
                    if (isNullOrEmpty(orgOrStuInfoReq.getMajorName())) {
                        transactionManager.rollback(status);
                        createImportTaskDetail("", "", taskId, REASON_INVALID_PARAM, String.valueOf(i + OFFSET_ROW));
                        taskStatus = TASK_STATUS_ERR;
                        continue;
                    }

                    // 校验专业是否存在
                    List<SmsOrgStructure> orgStructureList = smsOrgStructureMapper.selectList(new LambdaQueryWrapper<SmsOrgStructure>()
                            .eq(SmsOrgStructure::getOrgName, orgOrStuInfoReq.getMajorName())
                            .eq(SmsOrgStructure::getLevel, "4"));
                    if (orgStructureList.isEmpty()) {
                        transactionManager.rollback(status);
                        createImportTaskDetail("", "", taskId, REASON_ORG_MAJOR_NOT_EXIST, String.valueOf(i + OFFSET_ROW));
                        taskStatus = TASK_STATUS_ERR;
                        continue;
                    }

                    filterIdList = idList.stream().filter(aId -> {
                        for (SmsOrgStructure orgStructure : orgStructureList) {
                            if (aId.equals(String.valueOf(orgStructure.getId()))) {
                                return true;
                            }
                        }
                        return false;
                    }).collect(Collectors.toList());
                } else if (rangeType == CHARGE_PLAN_RANGE_TYPE_CLASS) {
                    if (isNullOrEmpty(orgOrStuInfoReq.getClassName())) {
                        transactionManager.rollback(status);
                        createImportTaskDetail("", "", taskId, REASON_INVALID_PARAM, String.valueOf(i + OFFSET_ROW));
                        taskStatus = TASK_STATUS_ERR;
                        continue;
                    }

                    // 校验班级是否存在
                    List<SmsOrgStructure> orgStructureList = smsOrgStructureMapper.selectList(new LambdaQueryWrapper<SmsOrgStructure>()
                            .eq(SmsOrgStructure::getOrgName, orgOrStuInfoReq.getClassName())
                            .eq(SmsOrgStructure::getLevel, "6"));
                    if (orgStructureList.isEmpty()) {
                        transactionManager.rollback(status);
                        createImportTaskDetail("", "", taskId, REASON_ORG_MAJOR_NOT_EXIST, String.valueOf(i + OFFSET_ROW));
                        taskStatus = TASK_STATUS_ERR;
                        continue;
                    }

                    filterIdList = idList.stream().filter(aId -> {
                        for (SmsOrgStructure orgStructure : orgStructureList) {
                            if (aId.equals(String.valueOf(orgStructure.getId()))) {
                                return true;
                            }
                        }
                        return false;
                    }).collect(Collectors.toList());
                } else if (rangeType == CHARGE_PLAN_RANGE_TYPE_USER) {
                    if (isNullOrEmpty(orgOrStuInfoReq.getStuNo())) {
                        transactionManager.rollback(status);
                        createImportTaskDetail("", orgOrStuInfoReq.getStuName(), taskId, REASON_INVALID_PARAM, String.valueOf(i + OFFSET_ROW));
                        taskStatus = TASK_STATUS_ERR;
                        continue;
                    }

                    List<SmsStudentInfo> studentInfoList = smsStudentInfoMapper.selectList(new LambdaQueryWrapper<SmsStudentInfo>()
                            .eq(SmsStudentInfo::getStuNo, orgOrStuInfoReq.getStuNo()));
                    if (studentInfoList.isEmpty()) {
                        transactionManager.rollback(status);
                        createImportTaskDetail("", "", taskId, REASON_CHARGE_STUDENT_INFO_NOT_EXIST, String.valueOf(i + OFFSET_ROW));
                        taskStatus = TASK_STATUS_ERR;
                        continue;
                    }

                    filterIdList = idList.stream().filter(aId -> {
                        for (SmsStudentInfo studentInfo : studentInfoList) {
                            if (aId.equals(studentInfo.getId())) {
                                return true;
                            }
                        }
                        return false;
                    }).collect(Collectors.toList());
                }

                // 校验是否在此收费计划范围内
                if (filterIdList.isEmpty()) {
                    transactionManager.rollback(status);
                    createImportTaskDetail("", "", taskId, REASON_CHARGE_ITEM_NOT_IN_PLAN, String.valueOf(i + OFFSET_ROW));
                    taskStatus = TASK_STATUS_ERR;
                    continue;
                }

                // 获取计划中保存的粒度id
                String id = filterIdList.get(0);

                // 获取计划中保存的粒度id对应的收费项
                List<SmsWnsChargeOrgItem> chargeItemList = this.list(new LambdaQueryWrapper<SmsWnsChargeOrgItem>()
                        .eq(SmsWnsChargeOrgItem::getOrgId, id)
                        .eq(SmsWnsChargeOrgItem::getPlanId, chargeItemBatchAddReq.getPlanId())
                        .in(SmsWnsChargeOrgItem::getCategoryDetailId, detailIdList));
                // 接收到的金额集合
                List<BigDecimal> amountList = orgOrStuInfoReq.getAmountList();
                int detailListSize = detailList.size();
                if (amountList.size() != detailListSize * 2) {
                    transactionManager.rollback(status);
                    createImportTaskDetail("", "", taskId, REASON_CHARGE_ITEM_NOT_IN_PLAN, String.valueOf(i + OFFSET_ROW));
                    taskStatus = TASK_STATUS_ERR;
                    continue;
                }

                // 创建一个临时Map用于存储每个CategoryDetailId对应的ChargeOrgItem
                Map<String, SmsWnsChargeOrgItem> categoryDetailToChargeItemMap = new HashMap<>();
                for (SmsWnsChargeOrgItem chargeItem : chargeItemList) {
                    categoryDetailToChargeItemMap.put(chargeItem.getCategoryDetailId(), chargeItem);
                }

                // 按照detailList的顺序创建排序后的chargeItemList
                List<SmsWnsChargeOrgItem> sortedChargeItemList = new ArrayList<>();
                for (SmsWnsChargeCategoryDetail detail : detailList) {
                    // 检查是否存在对应的ChargeOrgItem，若存在则添加到sortedChargeItemList
                    SmsWnsChargeOrgItem chargeItem = categoryDetailToChargeItemMap.get(detail.getId());
                    sortedChargeItemList.add(chargeItem);
                }

                for (int j = 0; j < detailListSize * 2; j++) {
                    // 通过计算简化条件判断
                    int effectiveIndex = j < detailListSize ? j : j - detailListSize;

//                    SmsWnsChargeCategoryDetail detail = detailList.get(effectiveIndex);
//                    // 过滤匹配到的收费项
//                    List<SmsWnsChargeOrgItem> filterChargeItemList = chargeItemList.stream()
//                            .filter(chargeItem -> chargeItem.getCategoryDetailId().equals(detail.getId()))
//                            .collect(Collectors.toList());
//
//                    if (filterChargeItemList.isEmpty()) {
//                        continue; // 如果没有找到匹配的收费项，则跳过当前迭代
//                    }
//
//                    SmsWnsChargeOrgItem chargeOrgItem = filterChargeItemList.get(0);

                    SmsWnsChargeOrgItem chargeOrgItem = sortedChargeItemList.get(effectiveIndex);
                    if (chargeOrgItem == null) {
                        continue;
                    }

                    // 更新收费项下所有学生应缴金额
                    if (j < detailListSize) {
                        chargeOrgItem.setAmount(amountList.get(j));
                    } else {
                        chargeOrgItem.setDiscountAmount(amountList.get(j));

                        this.updateById(chargeOrgItem);

                        // 优惠金额不能大于应缴金额
                        if (chargeOrgItem.getAmount().compareTo(chargeOrgItem.getDiscountAmount()) < 0) {
                            continue;
                        }
                        // 计算收费项应缴金额
                        BigDecimal totalAmount = chargeOrgItem.getAmount().subtract(chargeOrgItem.getDiscountAmount());

                        // 修改收费项下所有学生应缴金额
                        SmsWnsChargePlanStudentStatus studentStatus = new SmsWnsChargePlanStudentStatus();
                        studentStatus.setTotalAmount(totalAmount);
                        studentStatus.setNeedPaymentAmount(totalAmount);
                        smsWnsChargePlanStudentStatusMapper.update(studentStatus,
                                new LambdaQueryWrapper<SmsWnsChargePlanStudentStatus>()
                                        .eq(SmsWnsChargePlanStudentStatus::getChargeItemId, chargeOrgItem.getId()));
                    }
                }

                // 提交事务
                transactionManager.commit(status);
            } catch (Exception e) {
                e.printStackTrace();
                // 回滚事务
                transactionManager.rollback(status);
            } finally {
                if (status.isNewTransaction() && !status.isCompleted()) {
                    transactionManager.commit(status);
                }
            }
        }

        // 更新任务状态未已结束
        smsImportTask.setStatus(taskStatus);
        smsImportTaskMapper.updateById(smsImportTask);

        return new AsyncResult<>(CommonResult.success());
    }

    /**
     * 创建错误记录
     *
     * @param id     收费范围内元素id
     * @param name   元素名
     * @param taskId 任务id
     * @param reason 错误原因
     * @param row    错误行数
     */
    private void createImportTaskDetail(String id, String name, String taskId, String reason, String row) {
        SmsImportTaskDetail smsImportTaskDetail = new SmsImportTaskDetail();
        smsImportTaskDetail.setTaskId(taskId); // 任务id
        smsImportTaskDetail.setFailReason(reason); // 错误原因
        smsImportTaskDetail.setFailName(name); // 元素名
        smsImportTaskDetail.setFailNo(id); // 收费范围内元素id
        smsImportTaskDetail.setFailRow(row); // 错误行数
        smsImportTaskDetailMapper.insert(smsImportTaskDetail);
    }

    @Override
    public ResponseResult getStudentPaymentRecordByRangeType(Integer pageNum, Integer pageSize, Integer rangType, String planId, String collegeName, String majorName, String className, Integer paymentType) {
        if (isNullOrEmpty(rangType, planId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsWnsChargePlan smsWnsChargePlan = smsWnsChargePlanMapper.selectById(planId);
        if (isNullOrEmpty(smsWnsChargePlan)) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_PLAN_NOT_EXIST);
        }
        // 校验范围粒度
        if (!ChargePlanConstant.CHARGE_PLAN_RANGE_TYPE_LIST.contains(rangType)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<SmsWnsStudentPaymentRecordResp> studentPaymentRecordList = new ArrayList<>();
        Page<SmsUser> page = new Page<>(pageNum, pageSize);
        //构造查询条件,获取学生id集合
        LambdaQueryWrapper<SmsStudentInfo> studentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!isNullOrEmpty(collegeName)) {
            studentInfoLambdaQueryWrapper.eq(SmsStudentInfo::getStuCollege, collegeName);
        }
        if (!isNullOrEmpty(majorName)) {
            studentInfoLambdaQueryWrapper.eq(SmsStudentInfo::getStuMajor, majorName);
        }
        if (!isNullOrEmpty(className)) {
            studentInfoLambdaQueryWrapper.eq(SmsStudentInfo::getStuClass, className);
        }
        List<String> filterStuIdList = smsStudentInfoMapper.selectList(studentInfoLambdaQueryWrapper).stream().map(SmsStudentInfo::getId).collect(Collectors.toList());
        //构造通过学生id查用户id
        LambdaQueryWrapper<SmsUserStudentRelation> userStudentRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!filterStuIdList.isEmpty()) {
            userStudentRelationLambdaQueryWrapper.in(SmsUserStudentRelation::getStuId, filterStuIdList);
        } else {
            userStudentRelationLambdaQueryWrapper.in(SmsUserStudentRelation::getStuId, "");
        }
        List<String> filterUserIdList = smsUserStudentRelationMapper.selectList(userStudentRelationLambdaQueryWrapper).stream().map(SmsUserStudentRelation::getUserId).collect(Collectors.toList());
        //初始化 rangeType为专业或班级时
        List<String> orgIdList = new ArrayList<>();
        List<String> userIdList = new ArrayList<>();
        switch (rangType) {
            //专业
            case CHARGE_PLAN_RANGE_TYPE_MAJOR:
                //查询该计划下范围为专业的专业id集合
                List<String> majorIdListJson = smsWnsChargePlanMapper.selectList(new LambdaQueryWrapper<SmsWnsChargePlan>()
                                .eq(SmsWnsChargePlan::getId, planId)
                                .eq(SmsWnsChargePlan::getRangeType, CHARGE_PLAN_RANGE_TYPE_MAJOR))
                        .stream().map(SmsWnsChargePlan::getIdList).collect(Collectors.toList());
                if (!majorIdListJson.isEmpty()) {
                    String majorIdJson = majorIdListJson.get(0);
                    orgIdList = JSONObject.parseArray(majorIdJson, String.class);
                }
                break;
            //班级
            case CHARGE_PLAN_RANGE_TYPE_CLASS:
                //查询该计划下范围为班级的班级id集合
                List<String> classIdListJson = smsWnsChargePlanMapper.selectList(new LambdaQueryWrapper<SmsWnsChargePlan>()
                                .eq(SmsWnsChargePlan::getId, planId)
                                .eq(SmsWnsChargePlan::getRangeType, CHARGE_PLAN_RANGE_TYPE_CLASS))
                        .stream().map(SmsWnsChargePlan::getIdList).collect(Collectors.toList());
                if (!classIdListJson.isEmpty()) {
                    String classIdJson = classIdListJson.get(0);
                    orgIdList = JSONObject.parseArray(classIdJson, String.class);
                }
                break;
            //个人
            case CHARGE_PLAN_RANGE_TYPE_USER:
                //查询该计划下范围为个人的学生id集合
                List<String> stuIdListJson = smsWnsChargePlanMapper.selectList(new LambdaQueryWrapper<SmsWnsChargePlan>()
                                .eq(SmsWnsChargePlan::getId, planId)
                                .eq(SmsWnsChargePlan::getRangeType, CHARGE_PLAN_RANGE_TYPE_USER))
                        .stream().map(SmsWnsChargePlan::getIdList).collect(Collectors.toList());
                if (!stuIdListJson.isEmpty()) {
                    String stuIdJson = stuIdListJson.get(0);
                    List<String> stuIdList = JSONObject.parseArray(stuIdJson, String.class);
                    userIdList = smsUserStudentRelationMapper.selectList(new LambdaQueryWrapper<SmsUserStudentRelation>()
                            .in(SmsUserStudentRelation::getStuId, stuIdList)).stream().map(SmsUserStudentRelation::getUserId).collect(Collectors.toList());
                }
                break;
        }
        //获取范围为专业或班级下用户id集合
        if (rangType == CHARGE_PLAN_RANGE_TYPE_MAJOR || rangType == CHARGE_PLAN_RANGE_TYPE_CLASS) {
            LambdaQueryWrapper<SmsOrgUserRelation> orgUserRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (!filterUserIdList.isEmpty()) {
                orgUserRelationLambdaQueryWrapper.in(SmsOrgUserRelation::getUserId, filterUserIdList);
            } else {
                orgUserRelationLambdaQueryWrapper.in(SmsOrgUserRelation::getUserId, "");
            }
            if (!orgIdList.isEmpty()) {
                orgUserRelationLambdaQueryWrapper.in(SmsOrgUserRelation::getOrgId, orgIdList);
            } else {
                orgUserRelationLambdaQueryWrapper.in(SmsOrgUserRelation::getOrgId, "");
            }

            userIdList = smsOrgUserRelationMapper.selectList(orgUserRelationLambdaQueryWrapper)
                    .stream().map(SmsOrgUserRelation::getUserId).collect(Collectors.toList());
        }
        LambdaQueryWrapper<SmsUser> smsUserLambdaQueryWrapper = new LambdaQueryWrapper<SmsUser>().orderByDesc(SmsUser::getCreateTime);
        if (!userIdList.isEmpty()) {
            smsUserLambdaQueryWrapper.in(SmsUser::getId, userIdList);
        } else {
            smsUserLambdaQueryWrapper.in(SmsUser::getId, "");
        }
        smsUserMapper.selectPage(page, smsUserLambdaQueryWrapper);
        studentPaymentRecordList = page.getRecords()
                .stream()
                .filter(smsUser -> {
                    if (!isNullOrEmpty(paymentType)) {
                        //查询交费
                        List<SmsWnsChargePaymentRecord> paymentRecordList = smsWnsChargePaymentRecordMapper.selectList(new LambdaQueryWrapper<SmsWnsChargePaymentRecord>()
                                .eq(SmsWnsChargePaymentRecord::getEventId, planId)
                                .eq(SmsWnsChargePaymentRecord::getUserId, smsUser.getId())
                                .isNotNull(SmsWnsChargePaymentRecord::getPaymentAmount));
                        if (paymentType == PAYMENT_TYPE_IS) {
                            return !paymentRecordList.isEmpty();
                        } else if (paymentType == PAYMENT_TYPE_IS_NOT) {
                            return paymentRecordList.isEmpty();
                        }
                    }
                    return true;
                })
                .map(smsUser -> {
                    SmsWnsStudentPaymentRecordResp smsWnsStudentPaymentRecordResp = new SmsWnsStudentPaymentRecordResp();
                    List<String> stuIdList = smsUserStudentRelationMapper.selectList(new LambdaQueryWrapper<SmsUserStudentRelation>()
                            .eq(SmsUserStudentRelation::getUserId, smsUser.getId())).stream().map(SmsUserStudentRelation::getStuId).collect(Collectors.toList());
                    if (!stuIdList.isEmpty()) {
                        String stuId = stuIdList.get(0);
                        SmsStudentInfo smsStudentInfo = smsStudentInfoMapper.selectById(stuId);
                        if (!isNullOrEmpty(smsStudentInfo)) {
                            SmsStudentInfoResp smsStudentInfoResp = new SmsStudentInfoResp();
                            BeanUtils.copyProperties(smsStudentInfo, smsStudentInfoResp);
                            smsWnsStudentPaymentRecordResp.setStudentInfo(smsStudentInfoResp);
                            //查询交费
                            List<SmsWnsChargePaymentRecord> paymentRecordList = smsWnsChargePaymentRecordMapper.selectList(new LambdaQueryWrapper<SmsWnsChargePaymentRecord>()
                                    .eq(SmsWnsChargePaymentRecord::getEventId, planId)
                                    .eq(SmsWnsChargePaymentRecord::getUserId, smsUser.getId())
                                    .isNotNull(SmsWnsChargePaymentRecord::getPaymentAmount));
                            if (!paymentRecordList.isEmpty()) {
                                smsWnsStudentPaymentRecordResp.setIsPayment(true);
                                smsWnsStudentPaymentRecordResp.setPaymentAmount(paymentRecordList.get(0).getPaymentAmount());
                            } else {
                                smsWnsStudentPaymentRecordResp.setIsPayment(false);
                            }

                        }
                    }

                    return smsWnsStudentPaymentRecordResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(studentPaymentRecordList, (int) page.getTotal());
    }
}
